# -*-coding=utf-8-*-

import numpy as np


class Sphere():
    def __init__(self, position, radius, color, mode):
        self.radius = radius
        self.position = np.array(position, 'f')
        self.color = np.array(color, 'f')
        self.mode = mode

    def intersect(self, ray):
        """
        求交点
        """
        eps = 1e-4
        a = np.dot(ray.direction, ray.direction)
        O_C = ray.position - self.position
        b = 2 * np.dot(ray.direction, O_C)
        c = np.dot(O_C, O_C) - self.radius ** 2
        det = b**2 - 4*a*c
        if det <= 0.0000001:
            return None
        else:
            sqrt_det = np.sqrt(det)
            t = -b - sqrt_det
            if t > eps:
                t /= 2
            else:
                t = -b + sqrt_det
                if t > eps:
                    t /= 2
                else:
                    return None
        return (t, (ray.position+t*ray.direction-self.position) / self.radius, self.color, self.mode)

    def intersect_(self, ray):
        """
        求交点
        """
        # 球心到射线的距离
        center_to_ray = np.abs(np.linalg.norm(np.cross(self.position - ray.position, ray.direction)) / np.linalg.norm(ray.direction))
        # 射线和球面相交时
        if center_to_ray <= self.radius:
            # 射线起点到垂点距离
            length_1 = np.sqrt(np.abs(np.dot(self.position - ray.position, self.position - ray.position) - center_to_ray ** 2))
            # 交点到垂点距离
            length_2 = np.sqrt(self.radius ** 2 - center_to_ray ** 2)
            # 射线到交点距离比例值
            t = length_1 - length_2
            return (t, (ray.position+t*ray.direction-self.position) / self.radius, self.color, self.mode)
        else:
            return None
